﻿using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Account
{
    public class LoginAccountHandler : IRequestHandler<LoginAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;

        public LoginAccountHandler(IBaseRepository<AccountModel> accRepo)
        {
            this.accRepo = accRepo;
        }
        public Task<ApiResult<int>> Handle(LoginAccountCommand request, CancellationToken cancellationToken)
        {
            //实例化一个包装类
            ApiResult<int> result = new ApiResult<int>();
            var account = accRepo.GetAll().Where(x=>x.Name==request.Name).FirstOrDefault();
            if (account == null)
            {
                result.Code = ApiEnums.Fail;
                result.Msg = "登录名不存在";
                result.Data = -1;
            }
            else {
                if (account.Pass != request.Pass.GetMD5())
                {
                    result.Code = ApiEnums.Fail;
                    result.Msg = "密码不正确";
                    result.Data = -2;
                }
                else {
                    result.Code = ApiEnums.Success;

                    result.Msg = CreateTokenString(); //token
                    result.Data = 1;
                }
            } 
            return Task.FromResult(result);
        }

        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
